<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <a-tabs v-model="activeTab" @change="tabChange">
        <a-tab-pane v-for="item in tabs" :key="item.value" :tab="item.text"></a-tab-pane>
      </a-tabs>
      <!-- <a-row type="flex" align="middle" justify="start">
        <div class="search-item">
          <a-input-search placeholder="请输入商品名称" style="width: 320px" v-model="searchForm.name" />
        </div>
        <a-button type="primary" @click="gotoSearch"> 查询 </a-button>
      </a-row> -->
    </a-card>
    <div v-show="checkId.length" class="select-title">
      <a-alert :message="`已选择 ${checkId.length} 项`" type="info" show-icon />
    </div>
    <a-card :bordered="false" style="margin-top: 16px">
      <a-row type="flex" align="middle" justify="space-between">
        <a-button>全部分类</a-button>
        <a-row type="flex" align="middle" justify="end" style="margin-bottom: 16px">
          <a-button type="primary" style="margin-bottom: 0px" @click="onAdd(1)" icon="plus">新建</a-button>
          <a-dropdown :trigger="['click']">
            <a-menu slot="overlay" @click="(e) => this.checkSet(e.key)">
              <a-menu-item :key="0">批量禁用</a-menu-item>
              <a-menu-item :key="1">批量显示</a-menu-item>
              <a-menu-item :key="2">批量删除</a-menu-item>
            </a-menu>
            <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /> </a-button>
          </a-dropdown>
        </a-row>
      </a-row>
      <a-row type="flex" justify="space-around">
        <div style="width: 50%; padding-right: 30px" :bodyStyle="{ maxHeight: '580px', overflowY: 'auto' }">
          <div v-if="catList.length > 0">
            <el-tree
              :data="catList"
              @check-change="onCheck"
              @current-change="onSelect"
              @node-drop="nodeDrop"
              show-checkbox
              node-key="id"
              draggable
              :default-expand-all="true"
              :expand-on-click-node="true"
            >
              <span
                @mouseover="mouseover(data, node)"
                @mouseout="mouseout(data, node)"
                class="custom-tree-node flex-y-center flex-x-sb"
                style="flex: 1"
                slot-scope="{ node, data }"
              >
                <div class="flex-y-center">
                  <i v-if="node.expanded == false && node.childNodes.length" class="el-icon-folder"></i>
                  <i v-else class="el-icon-folder-opened"></i>
                  <span>{{ data.name }} (ID:{{ data.id }})</span>
                  <span v-if="data.is_show == 0" style="margin-left: 10px; color: #aaa"> (已禁用) </span>
                </div>
                <div>
                  <span v-show="mouseoverData.id == data.id">
                    <el-button v-show="isShowAdd" type="text" size="mini" @click.stop="mouseAdd(data, node)">
                      新增
                    </el-button>
                    <el-button type="text" size="mini" @click.stop="mouseDel(data)">{{
                      data.is_show == 0 ? '显示' : '禁用'
                    }}</el-button>
                    <el-button type="text" size="mini" @click.stop="checkSet(3, data.id)"> 删除 </el-button>
                  </span>
                </div>
              </span>
            </el-tree>
          </div>

          <a-empty v-else />
        </div>

        <a-affix :offset-top="100" style="flex: 1">
          <a-card :title="catInfo.updated_at ? '编辑分类' : '新增分类'">
            <a-form
              action=""
              method="post"
              @submit="submitAdd"
              :form="form"
              :label-col="{ span: 5 }"
              :wrapper-col="{ span: 12 }"
            >
              <a-form-item :labelCol="labelCol" :hidden="true" :wrapperCol="wrapperCol" label="父级分类">
                <a-input
                  v-decorator="[
                    'parent_id',
                    { rules: [{ pattern: /((^[1-9]\d*)|^0)(\.\d{0,0}){0,1}$/, message: '父级ID格式不争取' }] },
                  ]"
                  type="number"
                  :step="1"
                />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :hidden="true" :wrapperCol="wrapperCol" label="ID">
                <a-input
                  v-decorator="[
                    'id',
                    { rules: [{ pattern: /((^[1-9]\d*)|^0)(\.\d{0,0}){0,1}$/, message: 'ID格式不正确' }] },
                  ]"
                  type="number"
                  :step="1"
                />
              </a-form-item>
              <a-form-item
                v-if="catInfo.parent_name"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="父级分类"
                hasFeedback
              >
                <a-input :disabled="true" v-decorator="['parent_name']" />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="分类名称" hasFeedback>
                <a-input
                  v-decorator="[
                    'name',
                    {
                      rules: [
                        { required: true, message: '请填写名称' },
                        { max: 20, message: '名称不能大于20个字符' },
                      ],
                    },
                  ]"
                  placeholder="请填写分类名称"
                />
              </a-form-item>
              <a-form-item
                :hidden="true"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="排序"
                help="排序值越小排序越靠前"
                hasFeedback
              >
                <a-input
                  v-decorator="[
                    'sort',
                    {
                      rules: [
                        { required: false, message: '填写排序' },
                        { pattern: /((^[1-9]\d*)|^0)(\.\d{0,0}){0,1}$/, message: '排序不对' },
                      ],
                    },
                  ]"
                  type="number"
                  :step="1"
                />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="分类图标" hasFeedback>
                <div class="flex-col flex-x-sb">
                  <div>
                    <cyyUploadImg
                      :imgSrc="catInfo.pic_url"
                      @uploadSuccess="
                        (e) => {
                          catInfo.pic_url = e.data
                        }
                      "
                      @deleteImg="catInfo.pic_url = ''"
                      imgSizeText="100*100"
                    />
                  </div>
                </div>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否显示">
                <a-radio-group v-decorator="['is_show']">
                  <a-radio value="1"> 显示 </a-radio>
                  <a-radio value="0"> 禁用 </a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
                <a-button type="primary" html-type="submit" :loading="status.butLoading"> 保存 </a-button>
              </a-form-item>
            </a-form>
          </a-card>
        </a-affix>
      </a-row>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { list, save, del, statusAll, dragChange } from '@/api/goods/cat'
import { cyyUploadImg } from '@/components/CyyUi/index'
import pick from 'lodash.pick'

const statusLoading = {
  loading: true,
  showAdd: true, // 是否显示添加子分类按钮
  butLoading: false, // 提交按钮状态
  delLoading: false, // 删除按钮状态
  showLoading: false,
}
export default {
  name: '',
  components: {
    cyyUploadImg,
  },
  data() {
    return {
      activeTab: '1',
      tabs: [
        {
          value: '0',
          text: '产品库',
          path: 'purchaseGoodsManagerList',
        },
        {
          value: '1',
          text: '商品分类',
          path: 'purchaseGoodsManagerCat',
        },
        {
          value: '2',
          text: '商品上架记录',
          path: 'purchaseGoodsManagerGoodsRecord',
        },
        {
          value: '3',
          text: '商城上架记录',
          path: 'purchaseGoodsManagerShopRecord',
        },
      ],
      searchForm: {
        name: '',
        status: -1,
      },
      isShowAdd: true,
      showPreviwModal: false,
      previewImgSrc: '',
      catList: [],
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
      catInfo: {
        pic_url: '',
      },
      status: statusLoading,
      is_show: -1, // 获取列表状态
      checkId: [], // 选择中ID
      is_pic: true,
      mouseoverData: {
        id: '',
      },
    }
  },
  watch: {},
  computed: {},
  filters: {},
  mounted() {},
  methods: {
    // tab切换
    tabChange(e) {
      if (e == 1) return
      let item = this.tabs[e]
      console.log(item.path)
      this.$router.push({ name: item.path })
    },
    gotoSearch() {
      console.log(this.searchForm)
    },
    previewPic() {
      this.showPreviwModal = true
      this.previewImgSrc = this.catInfo.pic_url
    },
    updateCheck(res) {
      return false
    },
    getList() {
      list({ is_show: this.is_show }).then((res) => {
        console.log(res, 'list')
        this.status.loading = false
        this.catList = res.data.list
      })
    },
    // 鼠标移入事件
    mouseover(data, node) {
      // console.log(data, node, 'mouseover')
      if (node.level >= 3) {
        this.isShowAdd = false
      } else {
        this.isShowAdd = true
      }
      this.mouseoverData = data
    },
    mouseout(data, node) {
      this.mouseoverData = { id: '' }
    },
    mouseAdd(data, node) {
      console.log(data)
      this.catInfo = {
        id: 0,
        parent_id: data.id,
        parent_name: data.name,
        is_show: '1',
        pic_url: '',
        sort: 100,
        name: '',
      }
    },
    // 单个禁用
    mouseDel(data) {
      var status = ''
      if (data.is_show == 0) {
        status = 1
      } else {
        status = 0
      }
      this.checkSet(status, data.id)
    },
    // 拖拽完成触发
    async nodeDrop(node, fNode, position) {
      const formData = { id: node.data.id }
      switch (position) {
        case 'inner':
          formData.parent_id = fNode.data.id
          break

        default:
          formData.parent_id = fNode.data.parent_id
          break
      }

      try {
        const res = await dragChange(formData)
        if (res.code != 0) throw res
        this.$message.success(res.msg)
        this.getList()
      } catch (res) {
        this.$message.error(res.msg)
      }
    },
    onSelect(e, node) {
      console.log(e, node, 'select')
      this.catInfo = e
      // 当前为三级分类 是否可以添加下级
      if (node.level == 3) {
        this.showAdd = false
      } else {
        this.showAdd = true
      }
      // return

      // 是否可以添加分类图标
      this.is_pic = true

      return
    },
    onCheck(e, isSelect) {
      console.log(e, 'check')
      if (isSelect) {
        this.checkId.push(e.id)
      } else {
        this.checkId = this.checkId.filter((item) => {
          return item != e.id
        })
      }
      // 1.将选中id加入checkId
      return
    },
    getKeyData(e) {
      var indexArr = typeof e === 'number' ? [e] : e.split('-')
      var catList = this.catList
      var catInfo = {}
      if (indexArr.length === 1) {
        catInfo = catList[indexArr[0]]
      } else if (indexArr.length === 2) {
        catInfo = catList[indexArr[0]].children[indexArr[1]]
      } else if (indexArr.length === 3) {
        catInfo = catList[indexArr[0]].children[indexArr[1]].children[indexArr[2]]
      }
      console.log(this.catList, 'catList')
      return catInfo
    },
    onDel(id) {
      this.$message.loading({ content: '提交中...', key: 'del' })
      del({ id: id || this.catInfo.id }).then((res) => {
        this.$message.success({ content: res.msg, key: 'del' })
        if (res.code === 0) {
          this.getList()
        }
      })
    },
    /**
     * 批量操作 status 0 隐藏 1 显示 2 删除
     */
    checkSet(status, id) {
      var that = this
      var text = status === 0 ? '禁用' : status === 1 ? '显示' : '删除'
      this.$confirm({
        title: '是否确认' + text + '选中分类?',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          that.$message.loading({ content: '提交中...', key: 'checkSet' })
          statusAll({ status: status, id: id || that.checkId }).then((res) => {
            that.$message.success({ content: '提交成功!', key: 'checkSet', duration: 2 })
            that.getList()
          })
        },
        onCancel() {
          console.log('Cancel')
        },
        class: 'test',
      })
    },
    submitAdd(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.status.butLoading = true
          values.pic_url = this.catInfo.pic_url
          save(values).then((res) => {
            this.status.butLoading = false
            this.$message.success(res.msg)
            if (res.code === 0) {
              this.getList()
            }
          })
        }
      })
    },
    setDataForm() {
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.catInfo, ['name', 'sort', 'is_show', 'parent_id', 'id', 'parent_name']))
      })
    },
    onAdd(isNew = 0) {
      this.catInfo = {
        id: 0,
        parent_id: this.catInfo && this.catInfo.id > 0 && isNew === 0 ? this.catInfo.id : 0,
        parent_name: this.catInfo && this.catInfo.id > 0 && isNew === 0 ? this.catInfo.name : '顶级分类',
        is_show: '1',
        pic_url: '',
        sort: 100,
        name: '',
      }
    },
    updateShow(status) {
      this.is_show = status
    },
    selectImg(e) {
      this.catInfo.pic_url = e
    },
    uploadCb(e) {
      console.log(e)
      this.catInfo.pic_url = e.data
    },
  },
}
</script>

<style scoped>
.search-item {
  margin-right: 50px;
}
</style>
